<!DOCTYPE html>
<html>
<head>
    <title>Job Manage</title>
    <link rel="stylesheet" th:href="@{/css/sidebar.css}" />
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex; /* 使用 flex 布局 */
        }

        #content-container {
            flex: 1;
            margin-left: 20px;
        }

        #searchButton {
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #userTable {
            width: 100%;
            border-collapse: collapse;
        }

        #userTable th, #userTable td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        #userTable th {
            background-color: #4CAF50;
            color: white;
        }

        #prevButton, #nextButton {
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #prevButton[disabled], #nextButton[disabled] {
            background-color: #ccc;
            cursor: not-allowed;
        }

        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 10px;
        }

        .hidden {
            display: none;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div th:replace="sidebar.html :: sidebar"></div>
<div id="content-container">
    <button onclick="openForm()">添加任务</button>
    <div id="myModal" class="modal" style="display: none;">
        <div class="modal-content">
            <form id="myForm">
                <label for="jobName">任务名：</label>
                <input type="text" id="jobName" name="jobName"><br><br>

                <label for="jobExecuteClassPath">任务执行类：</label>
                <input type="text" id="jobExecuteClassPath" name="jobExecuteClassPath"><br><br>

                <label for="jobDescription">任务描述：</label>
                <input type="text" id="jobDescription" name="jobDescription"><br><br>

                <label for="jobCron">cron：</label>
                <input type="text" id="jobCron" name="jobCron"><br><br>

                <label for="jobExecuteStrategy">执行策略：</label>
                <select id="jobExecuteStrategy" name="jobExecuteStrategy"></select><br><br>

                <label for="jobType">任务类型：</label>
                <select id="jobType" name="jobType" onchange="toggleExecutorFields()"></select>

                <div id="executorFields" class="hidden">
                    <label for="executorIp">执行器IP：</label>
                    <input type="text" id="executorIp" name="executorIp"><br><br>

                    <label for="executorPort">执行器端口：</label>
                    <input type="text" id="executorPort" name="executorPort"><br><br>
                </div>
                <br><br>

                <label for="openCheckbox">开启任务：</label>
                <input type="checkbox" id="openCheckbox" onchange="toggleOpen()"><br><br>

                <button type="button" onclick="submitForm()">确定</button>
                <button type="button" onclick="closeForm()">取消</button>
            </form>
        </div>
    </div>
    <table id="userTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>任务名</th>
            <th>描述</th>
            <th>cron</th>
            <th>任务执行类</th>
            <th>是否生效</th>
            <th>是否开启</th>
            <th>执行策略</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
    <div>
        <button id="prevButton">Previous</button>
        <button id="nextButton">Next</button>
    </div>
</div>
<script>
    var currentPage = 1;
    var pageSize = 10;

    document.addEventListener('DOMContentLoaded', function() {
        queryBlogs();

        document.getElementById('searchButton').addEventListener('click', function() {
            queryBlogs();
        });

        document.getElementById('prevButton').addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage--;
                queryBlogs();
            }
        });

        document.getElementById('nextButton').addEventListener('click', function() {
            currentPage++;
            queryBlogs();
        });
    });

    function toggleExecutorFields() {
        var jobTypeSelect = document.getElementById('jobType');
        var executorFields = document.getElementById('executorFields');

        if (jobTypeSelect.value === 'remote') {
            executorFields.classList.remove('hidden');
        } else {
            executorFields.classList.add('hidden');
        }
    }

    function queryBlogs() {

        var requestData = {
            pageNo: currentPage,
            pageSize: pageSize
        };

        var headers = {
            'Content-Type': 'application/json',
            'token': localStorage.getItem('token') // 替换为实际的令牌值
        };

        fetch('/job/queryPage', {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(requestData)
        })
            .then(function(response) {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('Request failed with status: ' + response.status);
                }
            })
            .then(function(data) {
                if (data.code === 200) {
                    renderUserTable(data.data.dataList);
                    updatePagination(data.data.pageNo, data.data.total);
                } else {
                    console.error(data.msg);
                }
            })
            .catch(function(error) {
                console.error(error);
            });
    }

    function renderUserTable(dataList) {
        var tableBody = document.getElementById('userTable').getElementsByTagName('tbody')[0];
        tableBody.innerHTML = '';

        dataList.forEach(function(job) {
            var row = document.createElement('tr');

            row.innerHTML = `
            <td>${job.jobId}</td>
            <td>${job.jobName}</td>
            <td>${job.description}</td>
            <td>${job.cron}</td>
            <td>${job.executeClassPath}</td>
            <td>${job.enable}</td>
            <td>${job.open}</td>
            <td>${job.executeStrategy}</td>
        `;
            var detailTd = document.createElement('td')

            var detailButton = document.createElement('button')
            detailButton.innerText='详情'
            detailButton.addEventListener('click', function() {
                directToDetail(job.jobId)
            });

            var deleteButton = document.createElement('button')
            deleteButton.innerText='删除'
            deleteButton.addEventListener('click', function() {
                deleteJob(job.jobId)
            });
            detailTd.appendChild(detailButton)
            detailTd.appendChild(deleteButton)
            row.appendChild(detailTd)
            tableBody.appendChild(row);
        });
    }

    function updatePagination(currentPage, total) {
        document.getElementById('prevButton').disabled = (currentPage === 1);
        document.getElementById('nextButton').disabled = (currentPage * pageSize >= total);
    }

    function openForm() {
        var modal = document.getElementById("myModal");
        modal.style.display = "block";
    }

    function closeForm() {
        location.reload();
    }

    function submitForm() {
        var jobName = document.getElementById("jobName").value;
        var jobExecuteClassPath = document.getElementById("jobExecuteClassPath").value;
        var jobDescription = document.getElementById("jobDescription").value;
        var jobCron = document.getElementById("jobCron").value;

        // 获取执行策略下拉列表中的选中值
        var jobExecuteStrategySelect = document.getElementById("jobExecuteStrategy");
        var jobExecuteStrategy = jobExecuteStrategySelect.value;

        var jobTypeSelect = document.getElementById("jobType");
        var jobType = jobTypeSelect.value;

        var openCheckbox = document.getElementById("openCheckbox");
        var open = openCheckbox.checked ? 1 : 0;

        var executorIp = document.getElementById('executorIp').value;
        var executorPort = document.getElementById('executorPort').value;

        var params = {}
        params['executorIp'] = executorIp
        params['executorPort'] = executorPort

        var data = {
            jobName: jobName,
            executeClassPath: jobExecuteClassPath,
            description: jobDescription,
            cron: jobCron,
            open: open,
            jobType: jobType,
            params: params,
            executeStrategy: jobExecuteStrategy // 将执行策略添加到数据中
        };

        console.log('data', data)

        fetch('/job', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    location.reload();
                } else {
                    alert(result.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }


    function directToDetail(jobId) {
        var detailUrl = '/index/jobDetail?id=' + jobId
        window.location.href = detailUrl
    }

    function deleteJob(jobId) {
        fetch('/job/' + jobId, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    location.reload();
                } else {
                    alert(result.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function getJobType() {
        // 获取执行策略下拉列表
        var jobExecuteStrategySelect = document.getElementById("jobType");

        // 发送GET请求获取执行策略选项
        fetch('/job/jobType')
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    var options = result.data;
                    // 遍历选项，创建option元素并添加到下拉列表中
                    options.forEach(option => {
                        var optionElement = document.createElement("option");
                        optionElement.value = option.name;
                        optionElement.textContent = option.description;
                        jobExecuteStrategySelect.appendChild(optionElement);
                    });
                } else {
                    console.log(result.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function getExecuteStrategy() {
        // 获取执行策略下拉列表
        var jobExecuteStrategySelect = document.getElementById("jobExecuteStrategy");

        // 发送GET请求获取执行策略选项
        fetch('/job/executeStrategy')
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    var options = result.data;
                    // 遍历选项，创建option元素并添加到下拉列表中
                    options.forEach(option => {
                        var optionElement = document.createElement("option");
                        optionElement.value = option.name;
                        optionElement.textContent = option.description;
                        jobExecuteStrategySelect.appendChild(optionElement);
                    });
                } else {
                    console.log(result.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    getExecuteStrategy()
    getJobType()
    queryBlogs()
</script>
</body>
</html>